package dao;

import db.DBUtil;
import model.Supplier;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 供应商数据访问类，操作供应商数据库
 */
public class SupplierDAO {
    
    /**
     * 注册新供应商
     */
    public boolean registerSupplier(Supplier supplier) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO suppliers (supplier_id, name, address, contact_person, phone, password) " +
                         "VALUES (?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, supplier.getSupplierId());
            pstmt.setString(2, supplier.getName());
            pstmt.setString(3, supplier.getAddress());
            pstmt.setString(4, supplier.getContactPerson());
            pstmt.setString(5, supplier.getPhone());
            pstmt.setString(6, supplier.getPassword());
            
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            System.err.println("注册供应商失败: " + e.getMessage());
            return false;
        } finally {
            try {
                if (pstmt != null) pstmt.close();
                DBUtil.closeConnection(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 供应商登录
     */
    public Supplier login(String supplierId, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Supplier supplier = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM suppliers WHERE supplier_id = ? AND password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, supplierId);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                supplier = new Supplier();
                supplier.setSupplierId(rs.getString("supplier_id"));
                supplier.setName(rs.getString("name"));
                supplier.setAddress(rs.getString("address"));
                supplier.setContactPerson(rs.getString("contact_person"));
                supplier.setPhone(rs.getString("phone"));
                supplier.setPassword(rs.getString("password"));
            }
        } catch (SQLException e) {
            System.err.println("供应商登录查询失败: " + e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                DBUtil.closeConnection(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        return supplier;
    }
}
    